﻿<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller_Template {

	public $template = 'index';

	public function action_index()
	{
		$view = new View('welcome/index');
		
		$view->periodos = ORM::factory('periodo')
			->where('inicio', '>', strtotime('-1 Days'))
			->and_where('fim', '<=', strtotime('+15 Days'))
			->order_by('inicio')
			->find_all();
		
		$this->template->body = $view;
	}
	
	public function action_login()
	{
		$post = Validation::factory($_POST);
		$post->rule('usuario', 'not_empty')
			->rule('usuario', 'regex', array(':value', '/^[a-zA-Z_.]++$/iD'))
			->rule('senha', 'not_empty')
			->rule('senha', 'min_length', array(':value', '3'));
		
		if($post->check()):
		
			$usuario = ORM::factory('usuario')
				->where('usuario', '=', $post['usuario'])
				->and_where('senha', '=', $post['senha'])
				->find();
				
			if($usuario->loaded())
			{
				Session::instance()->set('usuario', serialize($usuario->as_array()));
				$this->request->redirect('calendario/index');
			}
			else {
				$errors = $post->errors('user');
				Flash::message('error', 'Usuário não encontrado!');
				
				$this->request->redirect('welcome/index');
			}
			
		endif;
	}
	

} // End Welcome
